<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>

      <el-col :span="12" :xs="24">
        <el-form class="login_form" :model="loginForm" ref="formRef" :rules="loginRules">
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input :prefix-icon="Lock" v-model="loginForm.password" type="password" show-password />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login" class="login_btn" :loading="loading">登陆</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import type { FormInstance, FormRules } from 'element-plus'
  import { User, Lock } from '@element-plus/icons-vue'
  import { loginFormData } from '@/api/user/type'
  import useUserStore from '@/store/modules/user'
  import { toast } from '@/utils/message'

  const loginForm = reactive<loginFormData>({
    username: 'admin',
    password: '111111',
  })

  const loginRules = reactive<FormRules<loginFormData>>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  })

  const formRef = ref<FormInstance>()
  const $router = useRouter()
  const $route = useRoute()
  const userStore = useUserStore()
  const loading = ref(false)
  function login() {
    formRef.value?.validate(async (valid) => {
      if (!valid) return
      try {
        loading.value = true
        await userStore.userLogin(loginForm)
        toast('登陆成功', 'success', true)
        $router.push({
          path: ($route.query.redirect as string) ?? '/',
        })
      } catch (error) {
        toast((error as Error).message, 'error', false)
      } finally {
        loading.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  .login_container {
    width: 100vw;
    height: 100vh;
    background-image: url('@/assets/images/background.jpg');
    background-repeat: no-repeat;
    background-size: cover;

    .el-col {
      position: relative;
      .login_form {
        position: absolute;
        width: 80%;
        top: 30vh;
        padding: 40px;
        background-image: url('@/assets/images/login_form.png');
        background-repeat: no-repeat;
        background-size: cover;
        h1 {
          color: #fff;
          font-size: 40px;
        }
        h2 {
          color: #fff;
          font-size: 20px;
          margin: 20px 0px;
        }
        .login_btn {
          width: 100%;
        }
      }
    }
  }
</style>
